package com.zx.mes.poi.controller;

import com.zx.mes.poi.entity.IsEntity;
import com.zx.mes.poi.service.TestService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;

@RestController
public class TestController {

    @Autowired
    private TestService testService;

    @GetMapping(value="download")
    public void downloadExcel(HttpServletRequest request, HttpServletResponse response, IsEntity isEntity){

        StringBuffer sbBuffer = new StringBuffer();
        sbBuffer.append("这是文件名");
        sbBuffer.append(LocalDateTime.now().toString());
        sbBuffer.append(".xls");
        String fileName =  sbBuffer.toString();

        //excel 写入数据 service层 TODO 这个自己注入进来
        HSSFWorkbook wb = this.testService.downloadExcel();

        this.setResponseHeader(response, fileName);
        try {
            OutputStream os = response.getOutputStream();
            wb.write(os);
            os.flush();
            os.close();
        } catch (IOException e) {
            //TODO 处理异常
        }
    }


    //发送响应流方法
    private void setResponseHeader(HttpServletResponse response, String fileName) {
        try {
            try {
                fileName = new String(fileName.getBytes(),"ISO8859-1");
            } catch (UnsupportedEncodingException e) {
                //TODO 处理异常
            }
            response.setContentType("application/octet-stream;charset=ISO8859-1");
            response.setHeader("Content-Disposition", "attachment;filename="+ fileName);
            response.addHeader("Pargam", "no-cache");
            response.addHeader("Cache-Control", "no-cache");
        } catch (Exception ex) {
            //TODO 处理异常
        }
    }

}
